﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using HighPerformanceLog.V2;

namespace XMLConfig
{
    public class ConfigManager
    {
        private readonly string configFilePath;
        private XDocument xmlDoc;

        public Dictionary<string, string> Settings { get; private set; }

        public ConfigManager(string xmlPath)
        {
            configFilePath = xmlPath;
            Load();
        }

        public void Load()
        {
            if (!File.Exists(configFilePath))
            {
                HWLogger.ErrorLog($"找不到 XML 文件：{configFilePath}");
                throw new FileNotFoundException("配置文件未找到", configFilePath);
            }

            xmlDoc = XDocument.Load(configFilePath);
            Settings = xmlDoc
                .Descendants("Setting")
                .ToDictionary(
                    s => s.Attribute("key").Value,
                    s => s.Attribute("value").Value
                );
        }

        public string GetValue(string key)
        {
            return Settings.ContainsKey(key) ? Settings[key] : null;
        }

        public void SetValue(string key, string value)
        {
            var setting = xmlDoc.Descendants("Setting")
                .FirstOrDefault(s => s.Attribute("key").Value == key);

            if (setting != null)
            {
                setting.Attribute("value").Value = value;
                Settings[key] = value;
            }
            else
            {
                var newSetting = new XElement("Setting",
                    new XAttribute("key", key),
                    new XAttribute("value", value)
                );
                xmlDoc.Root.Element("Settings").Add(newSetting);
                Settings[key] = value;
            }
        }

        public void Save()
        {
            xmlDoc.Save(configFilePath);
        }
    }
}
